﻿using ManYan.Domain.DomainService;
using ManYan.Domain.Model.Entity;
using ManYan.Repository.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ManYan.Infrastructure.DomainService
{
    public class BaseDomainService<T> : IBaseDomainService<T> where T : class, new()
    {
        public readonly IBaseRepository<T> _baseRepository;
        public BaseDomainService(IBaseRepository<T> baseRepository)
        {
            _baseRepository = baseRepository;
        }

        public bool AddEntity(T entity)
        {
            try
            {
                _baseRepository.BeginTran();
                _baseRepository.AddEntity(entity);
                _baseRepository.Commit();
                return true;
            }
            catch (Exception ex)
            {
                _baseRepository.RollbackTran();
                return false;
            }
        }

        public int DelEntity(Expression<Func<T, bool>> where)
        {
           return _baseRepository.DelEntity(where);
        }

        public int GetEntitiesCount(Expression<Func<T, bool>> where)
        {
           return _baseRepository.GetEntitiesCount(where);
        }

        public List<T> LoadEntityAll()
        {
            return _baseRepository.LoadEntityAll().ToList();
        }

        public virtual IEnumerable<T> LoadEntityEnumerable(Expression<Func<T, bool>> where, Expression<Func<T, DateTime?>> orderby, string asc, int pageIndex, int pageSize)
        {
            return _baseRepository.LoadEntityEnumerable(where, orderby, asc, pageIndex, pageSize);
        }

        public bool UpdateEntity(T entity)
        {
            try
            {
                _baseRepository.BeginTran();
                _baseRepository.UpdateEntity(entity);
                _baseRepository.Commit();
                return true;
            }
            catch (Exception ex)
            {
                _baseRepository.RollbackTran();
                return false;
            }
        }

        public T WhereLoadEntity(Expression<Func<T, bool>> where)
        {
            return _baseRepository.WhereLoadEntity(where);
        }
    }
}
